// ignore_for_file: prefer_const_constructors, avoid_unnecessary_containers, prefer_interpolation_to_compose_strings

import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/login/QGCatchVerifyAliPage.dart';
import 'package:junyeyishu/ui/sale/widgets/QGAlert.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';

class QGMineAuthentPage extends StatefulWidget {
  const QGMineAuthentPage({super.key});

  @override
  State<QGMineAuthentPage> createState() => _QGMineAuthentPageState();
}

class _QGMineAuthentPageState extends State<QGMineAuthentPage> {
  bool isImport = false;
  bool isAble = false;
  final nameController = TextEditingController();
  final identityController = TextEditingController();

  @override
  void dispose() {
    nameController.dispose();
    identityController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return QGScaffold(
       bgColor:Color(0xFF0C1012),
        title: '我的认证',
        body: GestureDetector(
          onTap: () {
            unfocus(context);
          },
          child: Stack(children: [
            Container(
              color: Color(0xFF0C1012),
              child: Column(children: [
                SizedBox(height: 10.rpx),
                buildInfo(),
                builExplain(),
              ]),
            ),
            Positioned(left: 0.rpx, bottom: 0.rpx, child: buildButton())
          ]),
        ));
  }

  buildInfo() {
    return Container(
      width: kScreenWidth,
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      padding: EdgeInsets.only(left: 15.rpx, right: 15.rpx),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.rpx),
          color: Color(0xFF232A32)),
      child: Column(
        children: [buildPassword(), buildIdentity(), buildPhone()],
      ),
    );
  }

  buildPassword() {
    return Row(
      children: [
        Expanded(
            child: Container(
          height: 55.rpx,
          decoration: BoxDecoration(
              border: Border(
                  bottom:
                      BorderSide(width: 0.5.rpx, color: Color(0xFF3D4854)))),
          child: Row(children: [
            buildTitle('姓名', 14, FontWeight.bold, Color(0xFFFFFFFF)),
            SizedBox(
              width: 10.rpx,
            ),
            Expanded(child: buildInput(nameController, '请输入真实姓名'))
          ]),
        ))
      ],
    );
  }

  buildIdentity() {
    return Row(children: [
      Expanded(
          child: Container(
        height: 55.rpx,
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(width: 0.5.rpx, color: Color(0xFF3D4854)))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildTitle('身份证号', 14, FontWeight.bold, Color(0xFFFFFFFF)),
            SizedBox(
              width: 10.rpx,
            ),
            Expanded(child: buildInput(identityController, '请输入身份证号')),
          ],
        ),
      ))
    ]);
  }

  buildPhone() {
    return Container(
        height: 55.rpx,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildTitle('手机号码', 14, FontWeight.bold, Color(0xFFFFFFFF)),
            buildPhoneNumber(User.current?.phone ?? "13000000000"),
          ],
        ));
  }

  buildTitle(String name, int size, FontWeight weight, Color color) {
    return Text(
      name,
      style: TextStyle(fontSize: size.rpx, fontWeight: weight, color: color),
    );
  }

  buildPhoneNumber(String name) {
    return Text(
      name.replaceFirst(new RegExp(r'\d{4}'), '****', 3),
      style: TextStyle(
          fontSize: 14.rpx,
          fontWeight: FontWeight.normal,
          color: Color(0xFFFFFFFF)),
    );
  }

  buildInput(controller, text) {
    return TextField(
      controller: controller,
      keyboardType: TextInputType.text,
      cursorColor: Color(0xFFFFFFFF),
      textAlign: TextAlign.end,
      style: TextStyle(color: Color(0xFFFFFFFF)),
      decoration: InputDecoration(
          hintText: text,
          hintStyle: TextStyle(color: Color(0xFF999999)),
          border: OutlineInputBorder(borderSide: BorderSide.none),
          contentPadding: EdgeInsets.zero,
          enabledBorder: InputBorder.none,
          focusedBorder: InputBorder.none),
      onChanged: (value) {
        checkInput();
      },
    );
  }

  builExplain() {
    return Container(
      padding: EdgeInsets.only(left: 25.rpx, right: 25.rpx),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 18.5.rpx,
          ),
          buildTitle('*实名认证仅限年满18周岁 （不含）到60周岁（含）之间的中国大陆用户', 12,
              FontWeight.normal, Color(0xFF999999)),
          SizedBox(
            height: 6.rpx,
          ),
          buildTitle('*您填写的实名认证信息，须和您的注册手机号所鄉定的身份信息一致', 12, FontWeight.normal,
              Color(0xFF999999)),
          SizedBox(
            height: 6.rpx,
          ),
          buildTitle('* 未经您的授权，您的身份信息不会用于其他用途', 12, FontWeight.normal,
              Color(0xFF999999)),
        ],
      ),
    );
  }

  buildButton() {
    return Container(
      width: kScreenWidth,
      padding: EdgeInsets.fromLTRB(20.rpx, 10.rpx, 20.rpx, 44.rpx),
      decoration: BoxDecoration(color: Color(0xFF0C1012)),
      child: Row(
        children: [
          Expanded(
            child: Container(
              height: 44.rpx,
              decoration: isImport || isAble
                  ? BoxDecoration(
                      gradient: const LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors: [Color(0xFF4AE3FF), Color(0xFF44FFF0)],
                      ),
                      borderRadius: BorderRadius.circular(10.rpx),
                    )
                  : BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors: [
                          const Color(0xFF4AE3FF).withOpacity(0.4),
                          const Color(0xFF44FFF0).withOpacity(0.4)
                        ],
                      ),
                      borderRadius: BorderRadius.circular(10.rpx),
                    ),
              child: TextButton(
                onPressed: (() {
                  toAuthent();
                }),
                child: Text('立即认证',
                    style: TextStyle(
                        fontSize: 14.rpx,
                        fontWeight: FontWeight.bold,
                        color: isImport || isAble
                            ? Color(0xFF111111)
                            : Color(0xFF999999))),
              ),
            ),
          ),
        ],
      ),
    );
  }

  checkInput() {
    var name = nameController.text;
    var identify = identityController.text;
    if (name.isNotEmpty && identify.isNotEmpty) {
      isImport = true;
      setState(() {});
    } else {
      isImport = false;
      setState(() {});
    }
  }

  toAuthent() {
    if (isImport == false) {
      return;
    }
    unfocus(context);

    var ctx = context;
    confirm() {
      // Navigator.of(context).pop();

      // showDialog(
      //     context: context,
      //     builder: (context) {
      //       return QGCatchVerifyAliPage(
      //           phone: User.current?.phone ?? "13000000000");
      //     }).then((value) {

      //   if (value is! Map) return;

        var param = {};
        var value = {};
        param['realName'] = nameController.text;
        param['idCard'] = identityController.text;
        param["captchaVerifyParam"] = value["captchaVerifyParam"];
        Map<String, dynamic> stringMap = param.cast<String, dynamic>();

        Network.post(url_u_factorAuthenticate, data: stringMap, context: ctx)
            .then((res) async {
          if (!res.success) {
            toast(res.msg);
            return;
          }
          toast(res.data["message"] ?? "");
          await Future.delayed(const Duration(seconds: 1));
          Navigator.of(ctx).pop();
          Navigator.of(ctx).pop();
          Navigator.of(ctx).pushNamed(pageMineHasAuthent);
        });
     // });
    }

    QGAlert.show(context,
        content: "认证成功后，实名信息将无法修改，请核实无误后再提交",
        confirm: "认证",
        onConfirm: confirm);
  }
}
